import { defineStore } from "pinia";
import { AuthState } from "@/stores/interface/auth";
import { getFlatMenuList, getShowMenuList } from "@/utils";
import { getAuthMenuListApi } from "@/api/modules/login";

export const useAuthStore = defineStore({
  id: "admin-auth",
  state: (): AuthState => ({
    role: undefined,
    authMenuList: []
  }),
  getters: {
    authMenuListGet: state => state.authMenuList,
    // 菜单权限列表 ==> 左侧菜单栏渲染，需要剔除 isHide == true
    showMenuListGet: state => getShowMenuList(state.authMenuList),
    // 菜单权限列表 ==> 扁平化之后的一维数组菜单，主要用来添加动态路由
    flatMenuListGet: state => getFlatMenuList(state.authMenuList)
  },
  actions: {
    async getAuthMenuList() {
      const { data } = getAuthMenuListApi();
      data.forEach((item: Menu.MenuOptions) => {
        //判断路由是否包含权限字段
        if (item.meta && item.meta.role && this.role) {
          item.meta.role.includes(this.role) && this.authMenuList.push(item);
        }
      });
    }
  },
  persist: {
    key: "admin-auth",
    paths: ["role"]
  }
});
